import React from 'react';
import { toJS } from 'mobx';
import { inject, observer } from 'mobx-react';
import { Row, Col, Spin, Button, Icon } from 'antd';
import {
  WeaAuth,
  WeaErrorPage,
  WeaTools,
  WeaNewScroll,
  WeaTable,
  WeaLocaleProvider,
} from 'ecCom';
import { WeaTableNew } from 'comsMobx';

const WeaTableMobx = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
@WeaTools.tryCatch(
  React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@xsdhwl`} msg={props.error || getLabel(385218, '对不起，该页面异常，请联系管理员！')} />,
  { error: '' },
)
@inject('docDocShareStore')
@observer
class DocOfShare extends React.Component {
  constructor(props) {
    super(props);
    this.isMouted = false;
  }
  componentDidMount() {
    this.isMouted = true;
  }
  componentWillUnmount() {
    const { docDocShareStore } = this.props;
    docDocShareStore.setState({ showSearchAd: false });
    this.isMouted = false;
  }
  doShareAddDelete =()=> {
    const { docDocShareStore, docid, type = '' } = this.props;
    const { comsWeaTableStore, selectedKeys, shareBatchDatas } = docDocShareStore;
    const isBatch = type === 'batch';
    if (isBatch) {
      const datas = shareBatchDatas.filter((data, index) => toJS(selectedKeys).indexOf(index) < 0);
      docDocShareStore.setState({ shareBatchDatas: datas, selectedKeys: [] });
    } else {
      const { selectedRowKeys } = comsWeaTableStore;
      docDocShareStore.deleteShare({ docid, shareId: `${selectedRowKeys}` });
    }
  }
  onCheckChange=(key, value)=> {
    const { docDocShareStore } = this.props;
    const { shareBatchOpParams } = docDocShareStore;
    shareBatchOpParams[key] = value;
    docDocShareStore.setState({ shareBatchOpParams: toJS(shareBatchOpParams) });
  }
  // 添加共享
  getShareAddModal=()=> {
    const { docDocShareStore, docid, type = '' } = this.props;
    const { shareAddVisible, conditions, shareBatchDatas } = docDocShareStore;
    const isBatch = type === 'batch';
    const _conditions = toJS(conditions);
    if (_conditions.length === 0) {
      return null;
    }
    return (
      <WeaAuth ecId={`${this && this.props && this.props.ecId || ''}_WeaAuth@cyhx1a`}
        title={getLabel(18645, '添加共享')}
        visible={shareAddVisible}
        conditions={_conditions}
        onOk={this.shareAddOnOk}
        onCancel={this.shareAddOnCancel}
      />
    );
  }

  shareAddOnOk=(v) => {
    const { docDocShareStore, docid, type = '' } = this.props;
    const { shareAddVisible, conditions, shareBatchDatas } = docDocShareStore;
    const isBatch = type === 'batch';
    docDocShareStore.setState({ shareAddVisible: false });

    if (v.objType == 2 && v.subcompany != undefined && v.subcompanyspan != undefined) {
      v.obj_id = v.subcompany;
      v.obj_idspan = v.subcompanyspan;
    }
    if (v.objType == 3 && v.department != undefined && v.departmentspan != undefined) {
      v.obj_id = v.department;
      v.obj_idspan = v.departmentspan;
    }
    shareBatchDatas.push(v);
    isBatch
      ? docDocShareStore.setState({ shareBatchDatas })
      : docDocShareStore.doShareAddSubmit({ ...v, docid });
  }
  shareAddOnCancel=()=>{ 
    const { docDocShareStore } = this.props;
    docDocShareStore.setState({ shareAddVisible: false })
  }

  // 批量共享 columns
  getColumns=()=> {
    const { docDocShareStore } = this.props;
    const { shareBatchTableCols } = docDocShareStore;
    return shareBatchTableCols.map((col) => {
      let render = () => null;
      if (col.dataIndex === 'from_Level') { // 安全级别
        render = (text, record) => (
          record.from_Level !== undefined ? `${record.from_Level} - ${record.to_Level}` : text
        );
      } else if (col.dataIndex === 'obj_id') { // 对象
        render = (text, record) => {
          let str = record.obj_id ? record.obj_idspan.replace(/\,/g, () => ' x ') : '';
          if (record.has_sub) str += `(${record.has_sub === '0' ? '不' : ''}${record.has_subspan})`;
          if (record.role_level) str += `(${record.role_levelspan})`;
          if (record.post_Level) str += `/${record.post_Levelspan}`;
          if (record.target_object_id) str += `(${record.target_object_idspan})`;
          return str;
        };
      } else if (col.dataIndex === 'download') { // 下载
        render = (text, record) => {
          if (record.seclevel == 1) { // 增加非查看时不显示可下载判断
            return !record.download ? text : record.download === '0' ? '' : record.downloadspan;
          }
        };
      } else {
        render = (text, record) => record[`${col.dataIndex}span`] || text;
      }
      return { ...col, render };
    });
  }
  getRowSelection=()=> {
    const { docDocShareStore } = this.props;
    const { selectedKeys } = docDocShareStore;
    return (
      {
        selectedRowKeys: toJS(selectedKeys),
        onChange: selectedRowKeys => docDocShareStore.setState({ selectedKeys: selectedRowKeys }),
      }
    );
  }
  render() {
    const { docDocShareStore, docid, type = '' } = this.props;
    const { loading, comsWeaTableStore, shareAddEditBtn,
       shareBatchDatas, selectedKeys } = docDocShareStore;
    const { selectedRowKeys } = comsWeaTableStore;
    const loadingNow = loading || comsWeaTableStore.loading;
    const isBatch = type === 'batch';
    let { hasDelBtn = 0, hasAddBtn = 0 } = shareAddEditBtn;
    if (isBatch) {
      hasDelBtn = 1;
      hasAddBtn = 1;
    }
    return (
      <div className="wea-doc-share">
        <div className="wea-table-edit">
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@klbzu6`} className="wea-table-edit-title" >
            <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ci8h3f`}>
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@khgex2`} style={{ width: 22 }}
                type="primary"
                title={getLabel(91, '删除')}
                size="small"
                disabled={!hasDelBtn || !`${isBatch ? selectedKeys : selectedRowKeys}`}
                onClick={this.doShareAddDelete}
              ><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@2ck3ux`} type="minus" /></Button>
              <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@g4gjax`} style={{ width: 22 }}
                type="primary"
                title={getLabel(1421, '新增')}
                size="small"
                disabled={!hasAddBtn}
                onClick={() => {
                        docDocShareStore.setState({ shareAddVisible: true })
                          .getAddShare({ docid, type });
                      }}
              ><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@lz9nnw`} type="plus" /></Button>
            </Col>
          </Row>
          <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@f4dlvw`} height={355} >
            <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@q5ukdc`} spinning={loadingNow} >
              {
                isBatch
                  ?
                  <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@6omzo9`}
                    columns={this.getColumns()}
                    dataSource={toJS(shareBatchDatas)}
                    rowSelection={this.getRowSelection()}
                  />
                  :
                  <WeaTableMobx ecId={`${this && this.props && this.props.ecId || ''}_WeaTableMobx@nx2467`}
                    comsWeaTableStore={comsWeaTableStore}
                  />
              }
            </Spin>
          </WeaNewScroll>
        </div>
        {this.getShareAddModal()}
      </div>
    );
  }
}

export default DocOfShare;
